import numpy as np

def parse_track(dstr):
    """
    解析轨迹字符串d为三元组np.array [ [x,y,t], ... ]
    """
    arr = []
    for seg in dstr.strip().split(":"):
        vals = seg.split(",")
        if len(vals) >= 3:
            x, y, t = vals[:3]
            arr.append([float(x), float(y), float(t)])
    return np.array(arr)

def rmse_track(track1, track2):
    """
    轨迹欧氏均方根距离
    """
    n = min(len(track1), len(track2))
    diff = track1[:n] - track2[:n]
    return np.sqrt((diff ** 2).sum(axis=1)).mean()

def avg_abs_diff_x(track1, track2):
    """
    X（横向）绝对值均值差
    """
    n = min(len(track1), len(track2))
    return np.abs(track1[:n, 0] - track2[:n, 0]).mean()

def track_similarity(d_gen, d_true):
    a1 = parse_track(d_gen)
    a2 = parse_track(d_true)
    return {
        "rmse_xyz": rmse_track(a1, a2),
        "x_abs_avg_diff": avg_abs_diff_x(a1, a2),
        "len_gen": len(a1),
        "len_true": len(a2),
        "final_x_gen": a1[-1,0],
        "final_x_true": a2[-1,0]
    }

# ======用法示例======
# 你的/生成轨迹字符串
d_my = '0,0,0:1,0,47:5,-1,63:13,-2,79:28,-4,95:47,-7,111:62,-9,127:71,-10,143:74,-12,159:77,-12,199:79,-13,247:88,-14,263:92,-14,279:97,-14,295:101,-16,311:105,-16,327:109,-16,343:111,-16,367:112,-16,399:113,-16,431:114,-16,536:116,-16,551:122,-16,568:126,-16,584:126,-16,831:125,-16,871:123,-16,895:123,-16,1215'
# 浏览器真实轨迹
d_true = '0,0,0:2,0,40:6,0,60:13,-1,90:28,-2,110:46,-6,150:62,-8,170:71,-9,200:76,-10,220:77,-10,240:80,-10,290:88,-13,320:92,-13,340:97,-15,360:101,-16,370:105,-16,380:109,-16,400:111,-16,420:112,-16,430:113,-16,500:114,-16,600:116,-16,650:122,-16,700:126,-16,800:126,-16,900:125,-16,950:123,-16,970:123,-16,1200'

sim = track_similarity(d_my, d_true)
print("rmse_xyz: ", sim["rmse_xyz"])
print("x_abs_avg_diff: ", sim["x_abs_avg_diff"])
print("len_my: ", sim["len_gen"], "len_true: ", sim["len_true"])
print("末点x:    你的轨迹:", sim["final_x_gen"], "真实轨迹:", sim["final_x_true"])